package org.apache.rocketmq.console.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.rocketmq.console.config.RMQConfigure;
import org.apache.rocketmq.console.script.dao.DeptInfoDao;
import org.apache.rocketmq.console.script.model.DeptInfo;
import org.apache.rocketmq.console.script.model.EnvInfo;
import org.apache.rocketmq.console.script.model.EnvironDic;
import org.apache.rocketmq.console.script.model.RegionInfo;
import org.apache.rocketmq.console.script.model.SysInfo;
import org.apache.rocketmq.console.script.service.EnvService;
import org.apache.rocketmq.console.script.service.ScriptService;
import org.apache.rocketmq.console.shiro.entity.UserInfo;
import org.apache.rocketmq.console.shiro.entity.UserPermission;
import org.apache.rocketmq.console.support.JsonResult;
import org.apache.rocketmq.console.util.JsonUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import org.apache.rocketmq.console.shiro.dao.UserInfoDao;
import org.apache.rocketmq.console.shiro.dao.UserPermissionDao;

@Controller
@RequestMapping("/envdic")
public class EnvController {
	@Autowired
	private RMQConfigure rmqConfigure;

	@Value("${rocketmq.config.regionName}")
	private String realmName;

	// private Logger logger = LoggerFactory.getLogger(EnvController.class);
	@Autowired
	public EnvService envService;
	@Autowired
	public ScriptService scriptService;
	@Autowired
	public DeptInfoDao deptInfoDao;
	@Autowired
	public UserPermissionDao userPermissionDao;
	@Autowired
	public UserInfoDao userInfoDao;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/findDeptByDeptCode.query", method = RequestMethod.POST)
	@ResponseBody
	public DeptInfo findDeptByDeptCode(@RequestBody String deptCode) {
		DeptInfo deptInfo = deptInfoDao.findOneByCode(deptCode);
		String sysCodesJson = deptInfo.getSysCodes();
		StringBuffer sb = new StringBuffer();
		List<String> deptInfoList = JSON.parseObject(sysCodesJson, List.class);
		if (deptInfoList.size() > 0) {
			for (String sysCode : deptInfoList) {
				sb.append(sysCode + ",");
			}
			deptInfo.setSysCodes(sb.toString().substring(0, sb.length() - 1));
		} else {
			deptInfo.setSysCodes("");
		}

		List<DeptInfo> deptInfos = new LinkedList<DeptInfo>();
		deptInfos.add(deptInfo);
		return deptInfo;
	}

	@RequestMapping(value = "/listAllDept.query", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> listAllDept() {
		Map<String, Object> map = listSysAndEnv();
		List<DeptInfo> deptInfos = deptInfoDao.findAll();
		List<Map<String, Object>> deptMapList = new LinkedList<Map<String, Object>>();
		for (DeptInfo deptInfo : deptInfos) {
			Map<String, Object> deptMap = new HashMap<>();
			deptMap.put("deptName", deptInfo.getName());
			deptMap.put("deptCode", deptInfo.getCode());
			deptMapList.add(deptMap);
		}
		map.put("deptInfos", deptMapList);
		return map;
	}

	@RequestMapping(value = "/listAllPermission.query", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> listAllPermission() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<UserInfo> userInfos = userInfoDao.findAll();
		List<Map<String, Object>> userInfoMapList = new LinkedList<Map<String, Object>>();
		for (UserInfo userInfo : userInfos) {
			Map<String, Object> deptMap = new HashMap<>();
			deptMap.put("name", userInfo.getName());
			deptMap.put("permissionId", userInfo.getPermissionId());
			userInfoMapList.add(deptMap);
		}
		map.put("userInfos", userInfoMapList);

		List<UserPermission> userPermissions = userPermissionDao.findAll();
		List<Map<String, Object>> userPermissionMapList = new LinkedList<Map<String, Object>>();
		for (UserPermission userPermission : userPermissions) {
			Map<String, Object> deptMap = new HashMap<>();
			deptMap.put("name", userPermission.getName());
			deptMap.put("id", userPermission.getId());
			userPermissionMapList.add(deptMap);
		}
		map.put("userPermissions", userPermissionMapList);
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/findEnvDicById.query", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findEnvDicById(@RequestBody String idJson) {
		List<Map<String, Object>> envMapList = new LinkedList<Map<String, Object>>();
		Map<String, Object> map = listSysAndEnv();
		Map<Object, Object> idMap = JsonUtil.obj2Map(idJson);
		int id = (int) idMap.get("id");

		EnvironDic environDic = envService.findOneEnvironDic(id);

		RegionInfo regionInfo = envService.findRegionInfoByCode(environDic.getRegionCode());
		String deptCodesJson = regionInfo.getDeptCodes();
		StringBuffer sb = new StringBuffer();
		if (deptCodesJson != null && !"".equals(deptCodesJson)) {
			List<String> deptCodesList = JsonUtil.string2Obj(deptCodesJson, List.class);
			if (deptCodesList.size() > 0) {
				for (String deptCode : deptCodesList) {
					sb.append(deptCode + ",");
				}
				environDic.setExitDeptCodes(sb.toString().substring(0, sb.length() - 1));
			}

		} else {
			environDic.setExitDeptCodes("");
		}

		String rmqclusterJson = environDic.getRmqcluster();
		StringBuffer sb2 = new StringBuffer();
		if (rmqclusterJson != null) {
			List<String> rmqclusterList = JsonUtil.string2Obj(rmqclusterJson, List.class);

			for (String rmqcluster : rmqclusterList) {
				sb2.append(rmqcluster + ",");
			}
			environDic.setRmqcluster(sb2.toString().substring(0, sb2.length() - 1));
		} else {
			environDic.setRmqcluster("");
		}

		List<EnvironDic> list = new LinkedList<>();
		list.add(environDic);
		map.put("environDicList", list);
		List<EnvInfo> envInfos = envService.findAllEnvInfo();
		for (EnvInfo envInfo : envInfos) {
			Map<String, Object> envMap = new HashMap<>();
			envMap.put("enviroName", envInfo.getName());
			envMap.put("enviroCode", envInfo.getCode());
			envMapList.add(envMap);
		}

		map.put("envMap", envMapList);
		return map;
	}

	@RequestMapping(value = "/getRealmName.query", method = RequestMethod.GET)
	@ResponseBody
	public JsonResult<String> realmName() {
		EnvironDic currentRegion = rmqConfigure.getCurrentRegion();
		if (currentRegion == null) {
			return null;
		}
		JsonResult<String> result = new JsonResult<String>(currentRegion.getRegionName());
		return result;
	}

	@RequestMapping(value = "/list.query", method = RequestMethod.GET)
	@ResponseBody
	public List<EnvironDic> list() {
		return envService.findAllDic();
	}

	@RequestMapping(value = "/listRegionAndEnv.query", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> listRegionAndEnv() throws Exception {

		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();

		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> envMapList = new LinkedList<Map<String, Object>>();
		List<Map<String, Object>> regionMapList = new LinkedList<Map<String, Object>>();
		EnvironDic environDic = envService.findOneByNameserveLike(rmqConfigure.getNamesrvAddr());
		int permissionId = userInfo.getPermissionId();
		if (permissionId == 1) {

			List<RegionInfo> regionInfos = envService.findAllRegionInfo();
			for (RegionInfo regionInfo : regionInfos) {
				Map<String, Object> regionMap = new HashMap<>();
				regionMap.put("regionName", regionInfo.getName());
				regionMap.put("regionCode", regionInfo.getCode());
				regionMapList.add(regionMap);
			}

		} else if (environDic != null) {
			Map<String, Object> regionMap = new HashMap<>();
			regionMap.put("regionName", environDic.getRegionName());
			regionMap.put("regionCode", environDic.getRegionCode());
			regionMapList.add(regionMap);
		}

		List<EnvInfo> envInfos = envService.findAllEnvInfo();
		for (EnvInfo envInfo : envInfos) {
			Map<String, Object> envMap = new HashMap<>();
			envMap.put("enviroName", envInfo.getName());
			envMap.put("enviroCode", envInfo.getCode());
			envMapList.add(envMap);
		}

		map.put("regionMap", regionMapList);
		map.put("envMap", envMapList);
		return map;

	}

	// {code={deptName=平台系统研发部, deptCode=W01000301040104}, sysCodes=FOSS,
	// newSysCodes=[{sysCode=BAMP, sysName=统一应用管理平台}]}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveDept.do", method = RequestMethod.POST)
	@ResponseBody
	public Object saveDept(@RequestBody Map<String, Object> deptInfoMap) {
		Map<String, String> code = (Map<String, String>) deptInfoMap.get("code");
		String deptCode = (String) code.get("deptCode");
		DeptInfo deptInfo = deptInfoDao.findOneByCode(deptCode);
		List<String> sysCodeList = new LinkedList<String>();
		String sysCode = (String) deptInfoMap.get("sysCodes");
		String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
		if (sysCode != null) {
			String[] sysCodes = StringUtils.tokenizeToStringArray(sysCode, CONFIG_LOCATION_DELIMITERS);
			if (sysCodes.length >= 1) {
				for (String sysCode1 : sysCodes) {
					sysCodeList.add(sysCode1);
				}
			}
		}
		List<Map<String, String>> newSysCodes = (List<Map<String, String>>) deptInfoMap.get("newSysCodes");
		if (newSysCodes != null) {
			for (Map<String, String> map : newSysCodes) {
				String newsysCode = map.get("sysCode");
				sysCodeList.add(newsysCode);
			}
		}
		deptInfo.setSysCodes(JSON.toJSONString(sysCodeList));
		try {
			deptInfoDao.save(deptInfo);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/savePermission.do", method = RequestMethod.POST)
	@ResponseBody
	public Object savePermission(@RequestBody Map<String, Object> permissionInfoMap) {
		Map<String, String> user = (Map<String, String>) permissionInfoMap.get("name");
		String userName = (String) user.get("name");
		UserInfo userInfo = userInfoDao.findByName(userName);

		Map<String, Object> permission = (Map<String, Object>) permissionInfoMap.get("permissionId");
		Integer permissionId = (Integer) permission.get("id");
		userInfo.setPermissionId(permissionId);
		try {
			userInfoDao.save(userInfo);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	// @RequiresPermissions({"rmq:admin","rmq:edit"}) // 权限管理;
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/save.do", method = RequestMethod.POST)
	@ResponseBody
	public Object save(@RequestBody Map<String, Object> envDicInfoMap) {
		EnvironDic saveenvironDic = new EnvironDic();
		Object object = envDicInfoMap.get("regionName");
		String regionCode = (String) ((Map<String, Object>) object).get("regionCode");
		String enviroCode = (String) ((Map<String, Object>) envDicInfoMap.get("enviroCode")).get("enviroCode");

		EnvironDic environDic = scriptService.findEnvironDicByRegionCodeAndEnviroCode(regionCode, enviroCode);
		if (environDic != null) {
			saveenvironDic.setId(environDic.getId());
		}

		String cluster = (String) envDicInfoMap.get("cluster");
		// String[] clusters = cluster.split(",");
		String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
		String[] clusters = StringUtils.tokenizeToStringArray(cluster, CONFIG_LOCATION_DELIMITERS);
		Set<String> clusterList = new HashSet<>();
		for (String cluster1 : clusters) {
			clusterList.add(cluster1);
		}
		String clusterJson = JsonUtil.obj2String(clusterList);

		String deptCode = (String) envDicInfoMap.get("deptCodes");
		if (deptCode != null) {
			// String[] clusters = cluster.split(",");
			String[] deptCodes = StringUtils.tokenizeToStringArray(deptCode, CONFIG_LOCATION_DELIMITERS);
			Set<String> deptCodesList = new HashSet<>();
			for (String deptCode1 : deptCodes) {
				deptCodesList.add(deptCode1);
			}
			String deptCodesListJson = JsonUtil.obj2String(deptCodesList);
			saveenvironDic.setDeptCodes(deptCodesListJson);
		}
		String nameserver = (String) envDicInfoMap.get("nameserver");
		String consoleIp = (String) envDicInfoMap.get("consoleIp");
		if (consoleIp != null) {
			saveenvironDic.setConsoleIp(consoleIp);
		}
		saveenvironDic.setRmqcluster(clusterJson);
		saveenvironDic.setEnviroCode(enviroCode);

		saveenvironDic.setEnviroName(envService.findEnvNameByEnvCode(enviroCode));
		saveenvironDic.setNameserver(nameserver);
		saveenvironDic.setRegionCode(regionCode);
		saveenvironDic.setRegionName(envService.findReginNameByRegionCode(regionCode));
		envService.saveEnvironDic(saveenvironDic);
		return true;
	}

	@RequestMapping(value = "/update.do", method = RequestMethod.POST)
	@ResponseBody
	public Object update(@RequestBody EnvironDic environDic) {
		String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
		System.out.println("environDic============" + environDic.getExitDeptCodes());
		Set<String> deptCodesList = new HashSet<String>();
		Set<String> rmqClusterList = new HashSet<String>();
		String existDeptCode = environDic.getExitDeptCodes();
		// String[] existOfferSysCodes = existOfferSysCode.split(",");
		if (existDeptCode != null) {
			String[] existDeptCodes = StringUtils.tokenizeToStringArray(existDeptCode, CONFIG_LOCATION_DELIMITERS);
			for (String existDeptCode1 : existDeptCodes) {
				deptCodesList.add(existDeptCode1);
			}
		}

		String deptCode = environDic.getDeptCodes();
		if (deptCode != null) {
			String[] deptCodes = StringUtils.tokenizeToStringArray(deptCode, CONFIG_LOCATION_DELIMITERS);
			for (String deptCode1 : deptCodes) {
				deptCodesList.add(deptCode1);
			}
		}

		String deptCodesJson = JsonUtil.obj2String(deptCodesList);
		RegionInfo regionInfo = envService.findRegionInfoByCode(environDic.getRegionCode());
		regionInfo.setDeptCodes(deptCodesJson);

		String rmqcluster = environDic.getRmqcluster();
		String[] rmqclusters = StringUtils.tokenizeToStringArray(rmqcluster, CONFIG_LOCATION_DELIMITERS);
		if (rmqclusters.length >= 1) {
			for (String rmqcluster1 : rmqclusters) {
				rmqClusterList.add(rmqcluster1);
			}
		}
		String rmqClusterListJson = JsonUtil.obj2String(rmqClusterList);
		environDic.setRmqcluster(rmqClusterListJson);

		return envService.saveRegionInfo(regionInfo) && envService.saveEnvironDic(environDic);

	}

	public Map<String, Object> listSysAndEnv() {
		List<Map<String, Object>> sysMapList = new LinkedList<Map<String, Object>>();
		List<Map<String, Object>> envMapList = new LinkedList<Map<String, Object>>();
		List<Map<String, Object>> regionMapList = new LinkedList<Map<String, Object>>();
		List<Map<String, Object>> clusterMapList = new LinkedList<Map<String, Object>>();
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();  
//		String username = user.username;
		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();

		// System.out.println("userInfo=========================" + userInfo.getName());
		EnvironDic environDic = null;
		String[] namesrvAddrList = rmqConfigure.getNamesrvAddr().split(";");
		for (String nameserverAddr : namesrvAddrList) {
			environDic = envService.findOneByNameserveLike(nameserverAddr);
			if (environDic != null) {
				break;
			}
		}

		List<String> tmp = new ArrayList<>();
		int permissionId = userInfo.getPermissionId();
		if (environDic == null || permissionId == 1) {

			List<EnvironDic> findAllEnvironDic = scriptService.findAllEnvironDic();
			for (EnvironDic environDic1 : findAllEnvironDic) {
				Map<String, Object> regionMap = new HashMap<>();
				if (!tmp.contains(environDic1.getRegionCode())) {
					regionMap.put("regionName", environDic1.getRegionName());
					regionMap.put("regionCode", environDic1.getRegionCode());
					regionMapList.add(regionMap);
				}
				tmp.add(environDic1.getRegionCode());

			}
			tmp = null;
		} else {
			Map<String, Object> regionMap = new HashMap<>();
			regionMap.put("regionName", environDic.getRegionName());
			regionMap.put("regionCode", environDic.getRegionCode());
			regionMapList.add(regionMap);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<SysInfo> findAllSysInfo = scriptService.findAllSysInfo();

		for (SysInfo sysInfo : findAllSysInfo) {
			Map<String, Object> sysMap = new HashMap<>();
			sysMap.put("sysCode", sysInfo.getCode());
			sysMap.put("sysName", sysInfo.getName());
			sysMapList.add(sysMap);
		}

		Map<String, Object> envMap = new HashMap<>();
		envMap.put("enviroName", null);
		envMap.put("enviroCode", null);
		envMapList.add(envMap);

		Map<String, Object> clusterMap = new HashMap<>();
		clusterMap.put("cluster", null);
		clusterMapList.add(clusterMap);

		map.put("sysMap", sysMapList);
		map.put("envMap", envMapList);
		map.put("regionMap", regionMapList);
		map.put("clusterMap", clusterMapList);
		return map;
	}
}
